package io.xxx.eve.robot.device;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.*;
import io.xxx.eve.task.TaskMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

@Component
@ChannelHandler.Sharable
public class ServerHandler extends SimpleChannelInboundHandler<String> {

    private final Map<String, Channel> channels = new HashMap<>();

    @Autowired
    private DeviceRepository deviceRepository;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        Channel channel = ctx.channel();
        channels.put(msg, channel);
        Optional<Device> deviceOptional = deviceRepository.findById(msg);
        if (deviceOptional.isEmpty()) {
            Device device = new Device();
            device.setId(msg);
            deviceRepository.save(device);
        }
    }

    public JSONObject sendMessage(String deviceId, TaskMessage message) {
        Channel channel = channels.get(deviceId);
        ChannelFuture future = channel.writeAndFlush(JSON.toJSONString(message));
        AtomicReference<Object> response = new AtomicReference<>();
        future.addListener(listener -> {
            if (listener.isSuccess()) {
                response.set(listener.get());
            } else {
                throw new RuntimeException();
            }
        });
        try {
            future.sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return JSON.parseObject(response.get().toString());
    }
}
